from sqlalchemy.orm import Session
from schema import Soil_Data_Processing_schema
from model import Soil_Data_Processing_model



def get_Soil_Data_Processing(db: Session, ID: int):
    return db.query(Soil_Data_Processing_model.Soil_data_processing).filter(Soil_Data_Processing_model.Soil_data_processing.ID == ID).first()


def get_all_Soil_Data_Processing(db: Session):
    return db.query(Soil_Data_Processing_model.Soil_data_processing).all()


def delete_Soil_Data_Processing(db: Session, ID):
    to_delete = db.query(Soil_Data_Processing_model.Soil_data_processing).filter(Soil_Data_Processing_model.Soil_data_processing.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Soil_Data_Processing(db: Session, Soil_Data_Processing: Soil_Data_Processing_schema.Soil_data_processing):
    db_Soil_Data_Processing = Soil_Data_Processing_model.Soil_data_processing(
        SoilID=Soil_Data_Processing.SoilID,
        SensorID=Soil_Data_Processing.SensorID,
        AIModelID=Soil_Data_Processing.AIModelID,
        RawDataJSON=Soil_Data_Processing.RawDataJSON,
        AnalysisResultJSON=Soil_Data_Processing.AnalysisResultJSON,
        RawDataRetrievalTime=Soil_Data_Processing.RawDataRetrievalTime,
        ProcessingTime=Soil_Data_Processing.ProcessingTime,
        Remarks=Soil_Data_Processing.Remarks,
    )
    db.add(db_Soil_Data_Processing)
    db.commit()
    db.refresh(db_Soil_Data_Processing)
    return db_Soil_Data_Processing


def update_Soil_Data_Processing(db: Session, ID, field_name, new_value):
    db_Soil_Data_Processing = db.query(Soil_Data_Processing_model.Soil_data_processing).filter(Soil_Data_Processing_model.Soil_data_processing.ID == ID).first()
    setattr(db_Soil_Data_Processing, field_name, new_value)
    db.commit()
    db.refresh(db_Soil_Data_Processing)
    return db_Soil_Data_Processing
